package com.gzx.plugin.data.xxljob;

import com.gzx.plugin.data.core.consts.CompanyConstants;
import com.gzx.plugin.data.core.sync.record.entity.DataSyncRecord;
import com.gzx.plugin.data.core.sync.record.service.DataSyncRecordService;
import com.gzx.plugin.data.wckj.service.DataWckjYwyhidService;
import com.gzx.plugin.data.wckj.service.ICaseApiService;
import com.gzx.plugin.data.wckj.service.TjzyWckjService;
import com.gzx.plugin.data.wckj.service.impl.CaseInfoScheduleService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.tenant.TenantContext;
import vip.xiaonuo.common.util.CommonDateUtil;

/**
 * @author zjt
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WckjDataSynchronizationJob {

    private final DataWckjYwyhidService dataWckjYwyhidService;

    private final DataSyncRecordService dataSyncRecordService;

    private final TjzyWckjService tjzyWckjService;

    private final ICaseApiService caseApiService;

    private final CaseInfoScheduleService caseInfoScheduleService;

    @XxlJob("wcDataSynchronizationJob")
    public void wcDataSynchronizationJob() {
        try {
            TenantContext.disableTenantFilter();
            if (isRunningAll()) {
                log.info("微财案件数据同步......开始");
                long startTime = System.currentTimeMillis();
                tjzyWckjService.startSynchronization(XxlJobHelper.getJobParam());
                insertRecord(CompanyConstants.WCKJ_COMPANY_CODE);
                log.info("微财案件数据同步......结束，耗时:{}", System.currentTimeMillis() - startTime);
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    @XxlJob("wcManualDataSynchronizationJob")
    public void wcManualDataSynchronizationJob() {
        try {
            TenantContext.disableTenantFilter();
            if (isRunningAll()) {
                log.info("微财案件数据同步......开始");
                long startTime = System.currentTimeMillis();
                tjzyWckjService.manualStartSynchronization(XxlJobHelper.getJobParam());
                insertRecord(CompanyConstants.WCKJ_COMPANY_CODE);
                log.info("微财案件数据同步......结束，耗时:{}", System.currentTimeMillis() - startTime);
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每半小时执行一次, @Scheduled(cron = "0 0,30 09-18 1 * *")
    @XxlJob("getWckjM4Job")
    public void getWckjM4Job() {
        try {
            TenantContext.disableTenantFilter();
            //只判断有无数据
            if (isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M4)) {
                log.info("微财案件M4项目5.1接口数据同步......开始");
                caseApiService.urgeCaseM4();
                insertRecord(CompanyConstants.WCKJ_PROJECT_CODE_M4);
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每秒执行一次
    @XxlJob("getWckjM4DetailJob")
//    @Scheduled(fixedDelay = 1000)
    public void getWckjM4DetailJob() {
        try {
            TenantContext.disableTenantFilter();
            if (isRunningByCount("M4+") > 0) {
                log.info("微财案件M4项目5.2接口数据同步......开始");
                caseInfoScheduleService.scheduleForCaseM4();
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每半小时执行一次, @Scheduled(cron = "0 0,30 09-18 1 * *")
    @XxlJob("getWckjM7Job")
    public void getWckjM7Job() {
        try {
            TenantContext.disableTenantFilter();
            //只判断有无数据
            if (isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M7)) {
                log.info("微财案件M7项目5.1接口数据同步......开始");
                caseApiService.urgeCaseM7();
                insertRecord(CompanyConstants.WCKJ_PROJECT_CODE_M7);
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每秒执行一次
    @XxlJob("getWckjM7DetailJob")
//    @Scheduled(fixedDelay = 1000)
    public void getWckjM7DetailJob() {
        try {
            TenantContext.disableTenantFilter();
            if (isRunningByCount("M7+") > 0) {
                log.info("微财案件M7项目5.2接口数据同步......开始");
                caseInfoScheduleService.scheduleForCaseM7();
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每半小时执行一次, @Scheduled(cron = "0 0,30 09-18 1 * *")
    @XxlJob("getWckjM12Job")
    public void getWckjM12Job() {
        try {
            TenantContext.disableTenantFilter();
            //只判断有无数据
            if (isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M13)) {
                log.info("微财案件M12项目5.1接口数据同步......开始");
                caseApiService.urgeCaseM12();
                insertRecord(CompanyConstants.WCKJ_PROJECT_CODE_M13);
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    //本方法每月1号9-18点，每秒执行一次
    @XxlJob("getWckjM12DetailJob")
//    @Scheduled(fixedDelay = 1000)
    public void getWckjM12DetailJob() {
        try {
            TenantContext.disableTenantFilter();
            if (isRunningByCount("M12+") > 0) {
                log.info("微财案件M12项目5.2接口数据同步......开始");
                caseInfoScheduleService.scheduleForCaseM12();
            }
        } catch (Exception e) {
            log.error("微财案件数据同步出现异常", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    private int isRunningByCount(String projectCode) {
        return dataWckjYwyhidService.isStartSynchronization(projectCode);
    }

    private boolean isRunningByRecord(String projectCode) {
        return dataSyncRecordService.getRecordByCurrentMonthAndCompanyCode(CommonDateUtil.getCurrentMonth(), projectCode);
    }

    private boolean isRunningAll() {
        //本月状态为0的数量是0条，并且本月这个公司还没有同步过并且M7和M12已经同步完成
        if (isRunningByCount(null) == 0 && isRunningByRecord(CompanyConstants.WCKJ_COMPANY_CODE) && !isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M4) && !isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M7) && !isRunningByRecord(CompanyConstants.WCKJ_PROJECT_CODE_M13)) {
            return true;
        }
        return false;
    }

    private void insertRecord(String code) {
        DataSyncRecord syncRecord = new DataSyncRecord();
        syncRecord.setCompanyCode(code);
        syncRecord.setCurrentMonth(CommonDateUtil.getCurrentMonth());
        syncRecord.setCreateTime(CommonDateUtil.getCurrentTimeStr());
        dataSyncRecordService.insert(syncRecord);
    }
}
